import axios from 'axios'
import { config } from './config'
import { errorMessage } from './status'
import { ElMessage } from 'element-plus'

const { resultCode } = config
const PATH_URL = import.meta.env.VITE_BASE_URL
// console.log(import.meta.env.VITE_BASE_URL, 'import.meta.env.VITE_BASE_URL')
// 创建axios实例
const service = axios.create({
  baseURL: PATH_URL, // api 的 base_url
  timeout: config.requestTimeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    // 增加token
    config.headers['Authorization'] = config.Authorization
    if (config.method === 'get' && config.params) {
      let url = config.url
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        if (config.params[key] !== void 0 && config.params[key] !== null) {
          url += `${key}=${encodeURIComponent(config.params[key])}&`
        }
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
      config.url = url
    }
    return config
  },
  (error) => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  (response) => {
    // console.log(response, 'response')
    if (response.config.responseType === 'blob') {
      // 如果是文件流，直接过
      return response
    } else if (response.data?.code === resultCode) {
      return response.data
    } else if (response.data?.code === 1001) {
      return response.data
    }
    const config = response.config
    // 查看文件接口放开
    if (config?.url.includes('/file/tarLook')) {
      console.log('这是一个查看接口！')
      return response
    } else {
      ElMessage.error(response.data.msg)
    }
    // return response.data
  },
  (error) => {
    console.log('err' + error) // for debug
    const msg = errorMessage(error.request.status)
    ElMessage.error(msg || error.msg)
    return Promise.reject(error)
  }
)

//通用下载
service.downloadFile = async (url, fileName, params, data, method = 'get') => {
  try {
    const res = await service({
      url,
      method: method,
      responseType: 'blob',
      params,
      data
    })
    const content = res.data
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(
      new Blob([content], { type: 'application/vnd.ms-excel' })
    )
    link.download = fileName
    link.click()
  } catch (error) {
    // window.$message.error('接口调用失败')
    return Promise.reject(error)
  }
}

//通用查看
service.lookFile = async (params, url = '/file/tarLook') => {
  try {
    const res = await service({
      url,
      method: 'get',
      responseType: '',
      params
    })
    const content = res?.data
    return content
  } catch (error) {
    // window.$message.error('接口调用失败')
    return Promise.reject(error)
  }
}

export { service }
